import base64
import json
import time

import requests
import execjs

requests = requests.session()


class Click():

    def __init__(self):
        # 获取gt 和 ch的值
        self.one_url = 'https://www.geetest.com/demo/gt/register-click'
        # 返回的是很多的js文件
        self.two_url = 'https://apiv6.geetest.com/gettype.php'
        # 返回pic 数据信息
        self.three_url = 'https://apiv6.geetest.com/get.php'
        # 返回的是click
        self.click_url = 'https://api.geevisit.com/ajax.php'
        self.headers = {
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Pragma": "no-cache",
            "Referer": "https://www.geetest.com/demo/click-float.html",
            "Sec-Fetch-Dest": "script",
            "Sec-Fetch-Mode": "no-cors",
            "Sec-Fetch-Site": "cross-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
            "^sec-ch-ua": "^\\^Chromium^^;v=^\\^122^^, ^\\^Not(A:Brand^^;v=^\\^24^^, ^\\^Microsoft",
            "sec-ch-ua-mobile": "?0",
            "^sec-ch-ua-platform": "^\\^Windows^^^"
        }
        self.challenge = None
        self.gt = None
        self._custom_url = "http://api.jfbym.com/api/YmServer/customApi"
        self._headers = {
            'Content-Type': 'application/json'
        }

    def one_request(self):
        params = {
            't': str(int(time.time() * 1000))
        }
        res = requests.get(self.one_url, headers=self.headers, params=params)
        self.challenge = res.json()['challenge']
        self.gt = res.json()['gt']
        print("第一次请求register-click：", res.text)

    def two_request(self):
        # 请求之后返回一堆js  目前不知道有什么用
        params = {
            'gt': self.gt,
        }
        requests.get(self.two_url, params=params, headers=self.headers)
        # 请求返回 c的值   感觉是过无感的
        params1 = {
            "gt": self.gt,
            "challenge": self.challenge,
            "lang": "zh-cn",
            "pt": "0",
            "client_type": "web",
            "w": "",
            "callback": "geetest_" + str(int(time.time() * 1000))
        }
        requests.get(self.three_url, params=params1, headers=self.headers)
        # click 返回的请求的地址
        params2 = {
            "gt": self.gt,
            "challenge": self.challenge,
            "lang": "zh-cn",
            "pt": "0",
            "client_type": "web",
            "w": "",
            "callback": "geetest_" + str(int(time.time() * 1000))
        }
        response = requests.get(self.click_url, headers=self.headers, params=params2)
        print("第二次请求ajax.php：", response.text)

        params3 = {
            "is_next": "true",
            "type": "click",
            "gt": self.gt,
            "challenge": self.challenge,
            "lang": "zh-cn",
            "https": "true",
            "protocol": "https://",
            "offline": "false",
            "product": "float",
            "api_server": "api.geevisit.com",
            "isPC": "true",
            "autoReset": "true",
            "width": "100%",
            "callback": "geetest_" + str(int(time.time() * 1000))
        }

        res = requests.get('https://api.geevisit.com/get.php', headers=self.headers, params=params3).text
        print("第三次请求get.php：", res)
        # print(json.loads(res[1:-1]))
        pic = json.loads(res[22:-1])['data']['pic']
        c = json.loads(res[22:-1])['data']['c']
        s = json.loads(res[22:-1])['data']['s']
        return pic, c, s

    def click_verify(self, image, extra=None, verify_type="30105"):
        payload = {
            "image": base64.b64encode(image).decode(),
            "extra": 'icon',
            "token": '7pE3vAgqNa3cDZ4iQULCogDd6oupapu9BVOLI9Fj32U',
            "type": verify_type
        }
        if extra:
            payload['extra'] = extra
        resp = requests.post(self._custom_url, headers=self._headers, data=json.dumps(payload))
        print(resp.text)
        return resp.json()['data']['data']

    def geetest_click(self, click_xy):
        # 坐标还原
        click_point_array = click_xy.split('|')
        click_point_true = []
        for item in click_point_array:
            x, y = item.split(',')
            point = str(int(int(x) / 344 * 10000)) + '_' + str(int(int(y) / 344 * 10000))
            click_point_true.append(point)
        click_true_str = ','.join(click_point_true)
        return click_true_str

    def there_request(self, pic, c, s):
        res = requests.get('https://static.geetest.com' + pic, headers=self.headers)
        open('click.png', 'wb').write(res.content)
        click_xy = self.click_verify(res.content)
        click_true_str = self.geetest_click(click_xy)
        js = execjs.compile(open('点选验证码.js', encoding='utf-8').read())
        print("传递参数：", click_true_str, pic, c, s, self.gt, self.challenge)
        w = js.call('get_w', click_true_str, pic, c, s, self.gt, self.challenge)
        print(w)
        return w

    def get_data(self, w):
        params = {
            "gt": self.gt,
            "challenge": self.challenge,
            "lang": "zh-cn",
            "pt": "0",
            "client_type": "web",
            "w": w,
            "callback": "geetest_" + str(int(time.time() * 1000))
        }
        url = "https://api.geevisit.com/ajax.php"
        time.sleep(2)
        response = requests.get(url, params=params, headers=self.headers)
        print("第四次请求ajax.php：", response.text)
        res = json.loads(response.text[22:-1])
        print("响应参数：", res)
        if res['data']['result'] == "success":
            return res['data']['validate']
        else:
            return ""

    def validate_request(self, validate):
        data = {
            "geetest_challenge": self.challenge,
            "geetest_validate": validate,
            "geetest_seccode": validate + "|jordan"
        }
        url = "https://www.geetest.com/demo/gt/validate-click"
        response = requests.post(url, headers=self.headers, data=data)
        print(response.text)

    def main(self):
        self.one_request()
        pic, c, s = self.two_request()
        w = self.there_request(pic, c, s)
        validate = self.get_data(w)
        self.validate_request(validate)


if __name__ == '__main__':
    jy = Click()
    jy.main()
